<template>
  <div class="blog-data">
    <!--  网格日志  -->
    <div class="data-view">
      <div class="grid-view">
        <div class="grid-left">
          <h3>Article Panel</h3>
          <GridLog :publicAticles="publicAticles"></GridLog>
        </div>
        <div class="grid-right">
          <div class="grid-area">
            <grid-area-item-count
              :icon="FileTextOutlined"
              :endVal="dataConfig.count"
              topTitle="文章数量"
              postFix="篇"
            ></grid-area-item-count>
            <grid-area-item-count
              :icon="EyeOutlined"
              :end-val="dataConfig.viewsCount"
              top-title="浏览量"
              post-fix="次"
            ></grid-area-item-count>
            <grid-area-item-count
              :icon="ReadOutlined"
              :end-val="dataConfig.readTime"
              top-title="平均阅读时长"
              post-fix="min"
            ></grid-area-item-count>
            <grid-area-item-count
              :icon="LikeOutlined"
              :end-val="dataConfig.likeCount"
              top-title="点赞量"
              post-fix=""
            ></grid-area-item-count>
            <grid-area-item-count
              :icon="MessageOutlined"
              :end-val="dataConfig.commentCount"
              top-title="评论"
              post-fix="条"
            ></grid-area-item-count>
            <grid-area-item-count
              :icon="HistoryOutlined"
              :end-val="dataConfig.updateTime"
              top-title="最新发布"
            ></grid-area-item-count>
          </div>
        </div>
      </div>
    </div>
    <!--  可视化面板  -->
    <div class="article-proportion">
      <div class="proportion-left">
        <div class="proportion-item cate">
          <v-chart class="chart" ref="chars" :option="cateOption" autoresize />
        </div>
        <div class="proportion-item access">
          <v-chart class="chart" :option="accessConfig" autoresize />
        </div>
      </div>
      <div class="proportion-right">
        <div class="proportion-item view">
          <v-chart class="chart" :option="option" autoresize />
        </div>
      </div>
    </div>
    <!--  最近提交动态 -->
    <div class="new-status">
      <div class="right-status-update">
        <div class="item">
          <v-chart class="chart" :option="option1" autoresize></v-chart>
        </div>
      </div>
      <div class="left-status-update">
        <div class="item" @mouseenter="mouseEnterHandler" @mouseleave="leaveHandler">
          <a-list
              class="comment-list"
              :header="`最新动态`"
              item-layout="horizontal"
              :data-source="newStatusList"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-comment :author="item.userName" :avatar="item.userAvatar">
                  <template #actions>
                    <span v-for="(action, index) in ['管理','查看']" :key="index" @click="articlesUtils(action,item)">{{ action }}</span>
                  </template>
                  <template #content>
                    <p>
                      {{ item.articleTitle }}
                    </p>
                  </template>
                  <template #datetime>
                    <a-tooltip >
                      <span>{{ item.publicTime}}</span>
                    </a-tooltip>
                  </template>
                </a-comment>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
//@ts-ignore
import GridLog from "@/components/grid-log.vue";
import { encryData } from '@/utils/index'
import {
  FileTextOutlined,
  EyeOutlined,
  ReadOutlined,
  LikeOutlined,
  MessageOutlined,
  HistoryOutlined,
} from "@ant-design/icons-vue";
//@ts-ignore
import GridAreaItemCount from "@/components/grid-area-item-count.vue";
import {
  publicArticleList,
  rightDataList,
  getDashboardData,
} from "@/api/blogData";
import  {getArticleList} from '@/api/article'
import {
  onMounted,
  ref,
  getCurrentInstance,
  nextTick,
  provide,
  reactive,
  computed,
    onBeforeUnmount,
  inject,
  watch,
} from "vue";
import { message } from "ant-design-vue";
// 引入 echarts所需要的包
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { PieChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from "echarts/components";
import VChart, { THEME_KEY } from "vue-echarts";
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import moment from "moment";
dayjs.extend(relativeTime);

use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
]);

// provide(THEME_KEY, 'dark'); // 是否启用黑夜模式

// /////////////////////////

// //////////////////////////

let cateOption = computed(() => {
  return {
    title: {
      text: "分类数量统计",
      left: 0,
    },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '0%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: chartData.cateOption.map((item:any) => item.cateName),
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '文章数量',
      type: 'bar',
      barWidth: '50%',
      data: chartData.cateOption.map((item:any) => item.count),
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      colorBy:'data'
    }
  ]
}
});

// 占比统计
const accessConfig = computed(() => {
  return {
    title:{
      text:"占比统计",
      left:0
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      show:true,
      bottom:0,
      left: 'center',
      textStyle:{
        fontSize:12
      },
      data:chartData.cateOption.map((item:any) => item.cateName)
    },
    series: [
      {
        name: '数量',
        type: 'pie',
        radius: ['20%', '40%'],
        avoidLabelOverlap: false,
        emphasis: {
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        label: {
          show: true,
          position: 'center',
          normal: {
            // 各分区的提示内容
            // params: 即下面传入的data数组,通过自定义函数，展示你想要的内容和格式
            formatter: "{b}",
            textStyle: {            // 提示文字的样式
              color: '#595959',
              fontSize: 12
            }
          }
        },
        data: chartData.cateOption.map((item:any) => {
          return {name:item.cateName,value:item.count}
        })
      }
    ]
  }
})

// 折线图
const option = computed(() => {
  return {
    title: {
      text: "文章发布走向",
      left: 0,
    },
  tooltip: {
    formatter: '{b}<br/>文章数量{c}',
  },
  grid: {
    left: '3%',
    right: '3%',
    bottom: '0%',
    containLabel: true
  },
  xAxis: {
    type: "category",
    data: chartData.cateOption.map((item:any) => item.cateName),
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: chartData.cateOption.map((item:any) => {
        return { name: item.cateName, value: item.count };
      }),
      type: "line",
      smooth: true,
      label:{
        show:true
      }
    },
  ],
}
})

// 获取文章数据
let publicAticles = ref([]);
let requestPublicArticles = async () => {
  let res: any = await publicArticleList();
  if (res.code !== 200) {
    message.error(res.message);
    return;
  }
  publicAticles.value = res.articles;
};

// 文章数据右侧数据列表
interface dataItem {
  count: number;
  viewsCount: number;
  readTime: number;
  likeCount: number;
  commentCount: number;
  updateTime: string;
}
let dataConfig = ref<dataItem>({
  count: 0,
  viewsCount: 0,
  readTime: 0,
  likeCount: 0,
  commentCount: 0,
  updateTime: "",
});

// 右侧数据配置信息
let getDataConfig = async () => {
  try {
    let res: any = await rightDataList();
    if (res.code !== 200) {
      message.error(res.message);
      return;
    } else {
      dataConfig.value = res.config;
    }
  } catch (e: any) {
    message.error(e.message);
  }
};

// 仪表盘数据
let chartData = reactive({
  cateOption: [],
});
let requestChartData = async () => {
  try {
    let res: any = await getDashboardData();
    if (res.code !== 200) return message.error(res.message);
    // console.log("dashboardConfig", res);
    chartData.cateOption = res.dashboardConfig.cateConfig;
  } catch (e: any) {
    message.error(e.message);
  }
};


// 获取最新动态
interface newStatueItem {
  actions?:Array<string>,
  author: string,
  avatar:string,
  content:string,
  datatime:string,
}
let newStatusList = ref<newStatueItem[]>([])
let viewBox = ref(0)

let requestNewStatus = async () => {
  try {
    let res:any = await getArticleList(1,10,0)
    if(res.code !== 200) {
      message.error(res.message)
      return
    }
    // console.log('最新动态',res)
    res.articles.map((item:any) => {
      item["publicTime"] = moment(item.publicTime).format('YYYY-MM-DD HH:mm')
    })
    newStatusList.value = res.articles
    nextTick(() => {
      moveHandler()
    })
    // console.log(newStatusList.value)
  }catch (e:any) {
    message.error(e.message)
  }
}

let moveHandler = () => {
  let listDom = document.querySelector('.ant-list') as HTMLElement
  let scrollDom = document.querySelector('.left-status-update') as HTMLElement
  let scorllTop = scrollDom.scrollHeight
  timer.value = setInterval(() => {
    let scrollDom = document.querySelector('.left-status-update') as HTMLElement
    if(scrollDom.scrollTop >= listDom.clientHeight - scrollDom.clientHeight){
      currentX.value =  0;
      scrollDom.scrollTo({top:currentX.value})
    }else {
      currentX.value+=1
      scrollDom.scrollTo({top:currentX.value})
    }
  },20)
}

let timer = ref()
let currentX = ref<number>(0)
let mouseEnterHandler = () => {
  clearInterval(timer.value)
}
let leaveHandler = () => {
  moveHandler()
}


let base = +new Date(1988, 9, 3);
let oneDay = 24 * 3600 * 1000;
let s = [[base, Math.random() * 300]];
for (let i = 1; i < 20000; i++) {
  let now = new Date((base += oneDay));
  s.push([+now, Math.round((Math.random() - 0.5) * 20 + s[i - 1][1])]);
}
let option1 = {
  tooltip: {
    trigger: 'axis',
    position: function (pt:any) {
      return [pt[0], '10%'];
    }
  },
  grid:{
    left: '3%',
    right: '4%',
    bottom: '0%',
    containLabel: true
  },
  title: {
    left: 'center',
    text: '内存'
  },
  toolbox: {
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      restore: {},
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'time',
    boundaryGap: false
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, '100%']
  },
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 20
    },
    {
      start: 0,
      end: 20
    }
  ],
  series: [
    {
      name: 'Fake Data',
      type: 'line',
      smooth: true,
      symbol: 'none',
      areaStyle: {},
      data: s
    }
  ]
};


requestNewStatus()
const data = [
  {
    actions: ['查看','管理'],
    author: 'Han Solo',
    avatar: 'https://tenfei05.cfp.cn/creative/vcg/800/new/VCG41N1307687091.jpg',
    content:
        'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
    datetime: dayjs().subtract(1, 'days'),
  },
];

// 查看
let articlesUtils = (action:any,articleItem:any) => {
  console.log('action',action,articleItem);
  if(action == '查看') {
    window.open(process.env.VUE_APP_BASE_DETAIL + encryData(articleItem.articleId))
  }
  
}


getDataConfig();
requestPublicArticles();
requestChartData();
onBeforeUnmount(() => {
  clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.blog-data {
  box-sizing: border-box;
  background-color: #fcfcfc;
  height: calc(100vh - 121px);
  overflow-y: auto;
  padding-bottom: 20px;
  &::-webkit-scrollbar {
    display: none;
  }
  .data-view {
    width: 100%;
    background-color: #fff;
    box-shadow: 0px 0px 10px 4px #eee;
    border-radius: 0px 0px 12px 12px;
    padding: 10px;
  }
  .grid-view {
    display: flex;
    .grid-left {
    }
    .grid-right {
      flex: 1;
      width: 100%;
    }
    .grid-area {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      height: calc(100%);
      .grid-area-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 33.33%;
        height: 50%;
        .grid-area-item-inner {
          cursor: pointer;
          display: flex;
          align-items: center;
          width: 90%;
          height: 90%;
          padding: 8px 12px;
          border-radius: 12px;
          transition: 0.3s all;
          &:hover {
            //background-color: white;
            //box-shadow: 0px 0px 6px 10px #f8f6f6;
          }
          .grid-area-item-inner-right {
            flex: 1;
            justify-content: start;
            align-items: center;
            margin: 0px 20px;
            h3 {
              font-size: 16px;
            }
            p {
              font-weight: bolder;
              margin-bottom: 0px;
              span {
                font-size: 14px;
                color: #000;
              }
            }
          }
        }
      }
    }
    ::v-deep .anticon svg {
      width: 35px;
      height: 35px;
    }
    ::v-deep .grid-area-item:nth-child(1) .anticon svg {
      color: blueviolet;
    }
    ::v-deep .grid-area-item:nth-child(2) .anticon svg {
      color: #0f9bf1;
    }
    ::v-deep .grid-area-item:nth-child(3) .anticon svg {
      color: #1966c9;
    }
    ::v-deep .grid-area-item:nth-child(4) .anticon svg {
      color: #f10303;
    }
    ::v-deep .grid-area-item:nth-child(5) .anticon svg {
      color: #ffa700;
    }
    ::v-deep .grid-area-item:nth-child(6) .anticon svg {
      color: #ff558d;
    }
  }
}

//可视化面板
.article-proportion {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px auto;
  min-height: 250px;
  height: 300px;
  .proportion-left {
    display: flex;
    width: 50%;
    height: 100%;
  }
  .proportion-right {
    width: 50%;
    height: 100%;
  }
  .proportion-item {
    border-radius: 12px;
    width: 48%;
    height: 100%;
    box-shadow: 0px 0px 5px 3px #f8f8f8;
    background-color: #fff;
    box-sizing: border-box;
    padding: 10px 2px;
    overflow: hidden;
    margin: 0 1%;
  }
}
.cate {
  width: 100%;
  height: 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
}
.proportion-right .view {
  width: 98%;
  height: 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
}

.new-status {
  display: flex;
  width: 100%;
  height: 400px;
  min-height: 200px;
  max-height: max-content;
  box-sizing: border-box;
  .left-status-update,.right-status-update {
    margin: 0 0.5%;
    width: 50%;
    height: 100%;
    display: flex;
    overflow: auto;
    box-shadow: 0px 0px 5px 3px #f8f8f8;
    background-color: #fff;
    border-radius: 12px;
    box-sizing: border-box;
    justify-content: center;
    &::-webkit-scrollbar {
      display: none;
    }
    .item {
      width: 98%;
      background-color: #fff;
      border-radius: 12px;
      box-sizing: border-box;
    }
  }
  .right-status-update {

  }
  .comment-list {
    .ant-list-item {
      border: none;
    }
  }
}

::v-deep.ant-list .ant-list-header {
  padding-left: 12px;
  font-weight: bolder;
  font-size: larger;
  height: 52px;
  border: none;
  width: 100%;
  background-color: white;
  z-index: 12;
  position: sticky;
  top: 0;
}
::v-deep.ant-comment .ant-comment-inner {
  padding: 0px;
}

@media screen and (max-width: 1250px) {
  .grid-view {
    flex-direction: column;
  }
  .grid-area-item {
    margin: 10px 0px;
  }
}

@media screen and (max-width: 480px) {
  .blog-data {
    .grid-view {
      .grid-right {
        .grid-area-item {
          width: 50% !important;
          margin: 10px 0px;
        }
      }
    }
  }
  // xi
  .article-proportion {
  }
}
</style>


